package com.example.homelicaisystem.control;

import com.example.homelicaisystem.entity.*;
import com.example.homelicaisystem.entity.DTO.InvestmentDetailDTO;
import com.example.homelicaisystem.entity.exception.UsedCashException;
import com.example.homelicaisystem.entity.exception.WrongEnoughMoney;

import com.example.homelicaisystem.services.CardService;
import com.example.homelicaisystem.services.InvestmentDetailService;
import com.example.homelicaisystem.services.InvestmentService;
import com.example.homelicaisystem.services.UserService;
import com.example.homelicaisystem.utils.HandleMoney;
import com.example.homelicaisystem.utils.Result;
import com.example.homelicaisystem.utils.UserUtil;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/investmentDetail")
@RestController
@Slf4j
public class InvestmentDetailControl {
    private final CardService cardService;
    private final InvestmentService investmentService;
    private final InvestmentDetailService investmentDetailService;
    private final UserService userService;

    public InvestmentDetailControl(InvestmentService investmentService, InvestmentDetailService investmentDetailService, CardService cardService, UserService userService) {
        this.investmentService = investmentService;
        this.investmentDetailService = investmentDetailService;
        this.cardService = cardService;
        this.userService = userService;
    }

    private static int BUY = 10;
    private static int SELL = 20;
    private static int BANK = 3;
    private static int SHARES = 1;

    @PostMapping("/list")
    public Result<ListWithCount<InvestmentDetail>> getList(@RequestBody InvestmentDetailDTO data) {
        log.debug("收到请求list请求。参数:{}", data);
        int userId = UserUtil.getUserId();
        data.setUserId(userId);
        Page<InvestmentDetail> res = investmentDetailService.getList(data);

        //数据库中金额单位为 分  前台单位为  元
        res.forEach(investmentDetail -> {
            investmentDetail.setMoney(HandleMoney.showMoney(investmentDetail.getMoney()));
        });
        return Result.ok(new ListWithCount<>(res.getTotal(), res));
    }

    @PostMapping("/createBuy")
    public Result<Integer> createBuy(@RequestBody InvestmentDetail data) {
        log.debug("收到请求createBuy请求。参数:{}", data);

        //拿到后台处理时，金钱单位为最小单位 分
        data.setMoney(HandleMoney.backendMoney(data.getMoney()));
        int userId = UserUtil.getUserId();
        data.setUserId(userId);

        //处理金额
        try {
            if (data.getModeId() == BANK) {
                cardService.decreaseBank(data);
            } else {
                userService.decreaseCash(data);
            }
        } catch (UsedCashException e) {
            throw new WrongEnoughMoney("金额不足");
        }
        //处理产品购买
        Investment investment = investmentService.buy(data);
        //创建交易明细记录
        data.setInvestmentId(investment.getId());
        data.setBuySell("购入");
        investmentDetailService.create(data);

        return Result.ok(null);
    }

    @PostMapping("/createSell")
    public Result<Integer> createSell(@RequestBody InvestmentDetail data) {
        log.debug("收到请求createSell请求。参数:{}", data);
        //拿到后台处理时，金钱单位为最小单位 分
        data.setMoney(HandleMoney.backendMoney(data.getMoney()));

        int userId = UserUtil.getUserId();
        data.setUserId(userId);

        if (data.getModeId() == BANK) {
            cardService.increaseBank(data);
        } else {
            userService.increaseCash(data);
        }
        //产品出售
        Investment investment = investmentService.sell(data);
        //创建交易明细记录
        data.setInvestmentId(investment.getId());
        data.setBuySell("售出");
        data.setInvestmentName(investment.getName());
        data.setRemarks(investment.getRemarks());
        investmentDetailService.create(data);
        return Result.ok(null);
    }


    @DeleteMapping("/deleteBuy/{id}")
    //没有返回值，泛型用？
    public Result<?> deleteBuy(@PathVariable int id) {
        log.debug("收到delete请求。");
        InvestmentDetail data = investmentDetailService.getInvestmentDetailById(id);
        if (data.getState() == BUY) {
            //对金额进行处理
            if (data.getModeId() == BANK) {
                cardService.increaseBank(data);
            } else {
                userService.increaseCash(data);
            }
            //根据删除的购入明细 修改investment数据
            investmentService.cancelBuy(data);
            //删除购入明细
            investmentDetailService.delete(id);
        }
        if (data.getState() == SELL) {
            try {
                if (data.getModeId() == BANK) {
                    cardService.decreaseBank(data);
                } else {
                    userService.decreaseCash(data);
                }
            } catch (UsedCashException e) {
                throw new UsedCashException("此产品已进行交易，无法删除");
            }
            //根据删除的售出明细 修改investment数据
            investmentService.cancelSell(data);
            //删除购入明细
            investmentDetailService.delete(id);
        }


        return Result.ok(null);
    }

}
